package protocol

import (
	"encoding/binary"
	"gitee.com/CloudGuan/rpc-go-backend/idlrpc/common"
)

const (
	INVALID_MSG   uint32 = iota //0 无效类型
	REQUEST_MSG                 // 1 调用请求
	RESPONESE_MSG               // 2 调用返回
	NOTRPC_MSG                  // 3 非RPC协议
)

const (
	IDL_SUCCESS uint32 = iota + 1
	IDL_SERVICE_NOT_FOUND
	IDL_SERVICE_ERROR
	IDL_RPC_TIME_OUT
)

const (
	SERVICE_RESOLVED = iota + 1 //状态
	SERVICE_UPDATING
)

var (
	RpcHeadSize, CallHeadSize, RespHeadSize int
)

// 协议包头 协议类型 协议长度
type RpcMsgHeader struct {
	Length uint32 //整个包长，包含头
	Type   uint32 //调用 返回 非rpc 请求
}

type RpcCallHeader struct {
	RpcMsgHeader
	ServiceUUID uint64 //服务UUID
	ServerID    uint32 //服务器实例ID
	CallID      uint32 //代理调用id
	MethodID    uint32 //方法id
}

type RpcCallRetHeader struct {
	RpcMsgHeader
	ServerID  uint32
	CallID    uint32
	ErrorCode uint32
}

func init() {
	RpcHeadSize = binary.Size(RpcMsgHeader{})
	CallHeadSize = binary.Size(RpcCallHeader{})
	RespHeadSize = binary.Size(RpcCallRetHeader{})
}

func BuildRespHeader(resp *ResponsePackage, srvID uint32, callID uint32, errcode uint32) {
	if resp == nil {
		return
	}

	if resp.Header == nil {
		resp.Header = &RpcCallRetHeader{}
	}

	resp.Header.Type = RESPONESE_MSG
	resp.Header.Length = uint32(RespHeadSize) + uint32(len(resp.Buffer))
	resp.Header.ServerID = srvID
	resp.Header.CallID = callID
	resp.Header.ErrorCode = errcode
}

func BuildNotFount(req *RpcCallHeader) (resp *ResponsePackage) {
	if req == nil {
		return
	}
	resp = &ResponsePackage{
		Header: &RpcCallRetHeader{},
	}
	resp.Header.Type = RESPONESE_MSG
	resp.Header.Length = uint32(RespHeadSize)
	resp.Header.ErrorCode = IDL_SERVICE_NOT_FOUND
	resp.Header.CallID = req.CallID
	resp.Header.ServerID = common.INVALIED_STUB_ID
	return
}

func BuildTimeOut(callID, ErrorCode uint32) (resp *ResponsePackage) {
	resp = &ResponsePackage{
		&RpcCallRetHeader{
			RpcMsgHeader{
				uint32(RespHeadSize),
				RESPONESE_MSG,
			},
			0,
			callID,
			ErrorCode,
		},
		nil,
	}

	return
}
